【问题标题】:Flutter WIth Django Rest Api to fetch dataFlutter WITH Django Rest Api 获取数据
【发布时间】:2021-10-02 12:56:02
【问题描述】:

我是 Flutter 的新手。我在 django rest api 中创建了一个小项目,用户可以通过 API 获取数据。我序列化数据及其工作。在前端,我正在为我的应用程序使用颤振。我确实在 pubspec.yaml 中添加了 http(0.13.3) 库。我在我的颤振项目中导入了这个包。现在我面临的问题是如何从 API 获取数据。

这是我在浏览器中访问我的 api 时获取数据的方式 -

[{"author":{"username":"jhinku","first_name":"jhinku","last_name":"mamoni"},"content":"????????"}]

在颤振 info.dart 中 -

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

final response = await http.get(MyAPIEndpoint);
Map response=jsonDecode(response.body);
@override
Widget build(BuildContext context) {
  return Container(
    padding: EdgeInsets.only(
      left: 12,
      bottom: bottomPadding,
    ),
    margin: EdgeInsets.only(right: 80),
    child: Column(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'response['author']['username']',
           style: StandardTextStyle.big,
        ),
        Container(height: 6),
        Text(
          desc ?? 'OK',
          style: StandardTextStyle.normal,
        ),
        Container(height: 6),
        Row(
          children: <Widget>[
            Icon(Icons.music_note, size: 14),
            Expanded(
              child: Text(
               'here is another text',
                maxLines: 9,
                style: StandardTextStyle.normal,
              ),
            )
          ],
        )
      ],
    ),
  );
}

我想从 REST-API 中输入作者。

Text(
        '@Author', #getting the author from the REST-API
        style: StandardTextStyle.big,
      ),

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您可以使用FutureBuilder,因为它对初学者来说最容易使用

    上面的答案也可以,但是这种方法更容易,尤其是当您对异步编程在 Flutter 中的工作原理知之甚少时

    
    
    import 'package:flutter/material.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      static const String _title = 'Flutter Code Sample';
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          title: _title,
          home: MyStatefulWidget(),
        );
      }
    }
    
    class MyStatefulWidget extends StatefulWidget {
      const MyStatefulWidget({Key? key}) : super(key: key);
    
      @override
      State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
    }
    
    
    class _MyStatefulWidgetState extends State<MyStatefulWidget> {
      final Future<Map<String,dynamic> _calculation(){
          //Perform your API Call here
          final response = await http.get(APIEndpoint)
          return jsonDecode(response)
      }
     
    
      @override
      Widget build(BuildContext context) {
        return DefaultTextStyle(
          style: Theme.of(context).textTheme.headline2!,
          textAlign: TextAlign.center,
          child: FutureBuilder<String>(  //This is mandatory to use
            future: _calculation, // a previously-obtained Future<Map> 
                                   //or null
            builder: (BuildContext context, 
                           AsyncSnapshot<Map<String,dynamic>> snapshot) {
              List<Widget> children;
              if (snapshot.hasData) {
                       // We have received the data here
                      //You can modify this code according to your case
                children = Container(
                       padding: EdgeInsets.only(
                       left: 12,
                       bottom: bottomPadding,
                       ),
        margin: EdgeInsets.only(right: 80),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              '$snapshot['author']['username']',
               style: StandardTextStyle.big,
            ),
            Container(height: 6),
            Text(
              desc ?? 'OK',
              style: StandardTextStyle.normal,
            ),
            Container(height: 6),
            Row(
              children: <Widget>[
                Icon(Icons.music_note, size: 14),
                Expanded(
                  child: Text(
                   'here is another text',
                    maxLines: 9,
                    style: StandardTextStyle.normal,
                  ),
                )
              ],
            )
          ],
        ),
      );
    }
              } else if (snapshot.hasError) {
                       // The asynchronous operation failed
                children = <Widget>[
                  const Icon(
                    Icons.error_outline,
                    color: Colors.red,
                    size: 60,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 16),
                    child: Text('Error: ${snapshot.error}'),
                  )
                ];
              } else {
               // snapshot.hasData is false so the data is still loading
                children = const <Widget>[
                  SizedBox(
                    child: CircularProgressIndicator(),
                    width: 60,
                    height: 60,
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 16),
                    child: Text('Awaiting result...'),
                  )
                ];
              }
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: children,
                ),
              );
            },
          ),
        );
      }
    }
    

    这里的_calculation 只是对任何异步操作的模拟,例如您的情况下的网络调用。您可以在此处添加您的网络调用和相关逻辑

    FutureBuilder 将在AsyncSnapshot&lt;T&gt; 中实现不同的状态,因此可以向用户显示操作正在进行中

    【讨论】:

    • 这个例子取自Flutter Docs
    • 我确实用@JigarFumakiya 的回答编辑了这个问题,但它没有用。
    • 嘿@Cavinblake,我试图用我希望你做的事情来编辑我的答案,看看这是否对你有帮助,如果有帮助,请投票并将解决方案标记为已接受
    • 在你编辑之后我还需要使用未来的构建器吗?
    • 那我的朋友,这是你学习的时候了,也只是申请,我已经给你上面的模板和cmets,所以我想编辑代码应该很容易吧?
    【解决方案2】:

    这里是你可以从 API 获取数据。

    final response = await http.get(APIEnpoint);
    
    Map response=jsonDecode(response.body);
    response['author']['username'] ---> here what you want
    response['author']['first_name'] -->Change key values and get all data.
    

    您可以将此 API 调用放在 init 方法中,获取数据后您可以设置状态

    【讨论】:

    • 我确实用你的解决方案编辑了这个问题,它给了我一堆错误。
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 2022-01-12
    • 2018-11-10
    • 2022-07-04
    • 2019-08-27
    • 2020-08-03
    • 2017-10-30
    • 2022-01-24
    相关资源
    最近更新 更多