【问题标题】:API calls in flutterFlutter 中的 API 调用
【发布时间】:2022-01-14 12:19:12
【问题描述】:

我是 Flutter 的新手,我正在尝试设计一个通过车牌提取信息的应用程序。我已经按照这个关于 API 的教程:https://docs.flutter.dev/cookbook/networking/fetch-data。对于 API,我需要指定我在本教程中使用的车牌号,其中保存了来自文本字段的文本:https://docs.flutter.dev/cookbook/forms/retrieve-input。我似乎无法弄清楚如何从文本字段中获取文本然后进行 API 调用。

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';


void main() => runApp(const MyApp());

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://v1.motorapi.dk/vehicles/'),
       headers: {"X-AUTH-TOKEN": "rfrzsucnc7eo3m5hcmq6ljdzda1lz793"});

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

//headers: {"X-AUTH-TOKEN": "rfrzsucnc7eo3m5hcmq6ljdzda1lz793"}

class Album {
  final String registration_number;
  final String status;
  final String type;
  final String use;
  final String first_registration;
  final String vin;
  final int doors;
  final String make;
  final String model;
  final String variant;
  final String model_type;
  final String color;
  final String chasis_type;
  final String engine_power;
  final String fuel_type;
  final String RegistreringssynToldsyn;
  final String date;
  final String result;

  Album({
    required this.registration_number,
    required this.status,
    required this.type,
    required this.use,
    required this.first_registration,
    required this.vin,
    required this.doors,
    required this.make,
    required this.model,
    required this.variant,
    required this.model_type,
    required this.color,
    required this.chasis_type,
    required this.engine_power,
    required this.fuel_type,
    required this.RegistreringssynToldsyn,
    required this.date,
    required this.result,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      registration_number: json['registration_number'],
      status: json['status'],
      type: json['type'],
      use: json['use'],
      first_registration: json['first_registration'],
      vin: json['vin'],
      doors: json['doors'],
      make: json['make'],
      model: json['model'],
      variant: json['variant'],
      model_type: json['model_type'],
      color: json['color'],
      chasis_type: json['chasis_type'],
      engine_power: json['engine_power'],
      fuel_type: json['fuel_type'],
      RegistreringssynToldsyn: json['RegistreringssynToldsyn'],
      date: json['date'],
      result: json['result'],
    );
  }
}


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Retrieve Text Input',
      home: MyCustomForm(),
    );
  }
}

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({Key? key}) : super(key: key);

  @override
  _MyCustomFormState createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Retrieve Text Input'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: TextField(
          controller: myController,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // When the user presses the button, show an alert dialog containing
        // the text that the user has entered into the text field.
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // Retrieve the text the that user has entered by using the
                // TextEditingController.
                content: Text(myController.text),
              );
            },
          );
        },
        tooltip: 'Show me the value!',
        child: const Icon(Icons.text_fields),
      ),
    );
  }
}

【问题讨论】:

  • 您需要初始化模型类并将模型类的字段传递给文本、图像和您需要的任何地方。
  • 看看未来的构建器如何以同样的方式处理数据快照:docs.flutter.dev/cookbook/networking/fetch-data
  • 如果您从 API 获取数据,请参考我的回答 hereherehere 希望对您有所帮助

标签: flutter api


【解决方案1】:

你错过了这个方法

@override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

【讨论】:

  • 请记住,Stack Overflow 不(只是)旨在解决眼前的问题,而是(也)帮助未来的读者理解解决方案,以便他们可以将其应用于类似的问题,或者变得更好理解代码。鉴于此,请不要只发布代码。你能edit你的答案包括解释你在做什么以及为什么你认为这是最好的方法吗?
【解决方案2】:
change your code for this

// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  TextEditingController myController ;

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }
@override
  void initState() {
    super.initState();
    myController=TextEditingController();
    futureAlbum = fetchAlbum();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Retrieve Text Input'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: TextField(
          controller: myController,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // When the user presses the button, show an alert dialog containing
        // the text that the user has entered into the text field.
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // Retrieve the text the that user has entered by using the
                // TextEditingController.
                content: Text(myController.text),
              );
            },
          );
        },
        tooltip: 'Show me the value!',
        child: const Icon(Icons.text_fields),
      ),
    );
  }

【讨论】:

    猜你喜欢
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多