【问题标题】:How can i display a button based on http response in flutter我如何在颤动中显示基于http响应的按钮
【发布时间】:2020-10-21 05:02:00
【问题描述】:

我正在向 Flutter 中的端点发出 http 请求,根据我的响应,我想显示一个按钮,但它不起作用,请问有人可以帮助我吗?我是新来的。端点需要两个参数,即用户 ID 和代理 ID,我都是从共享首选项文件中获取的。

userId = b6caf34c-a425-4710-a3ee-aa22a382882a

agentId : 57 请有人帮助我。

这是我的服务文件:

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class CallApi{
    final String _url = 'http://api.ergagro.com:112/';

    postData(data, apiUrl) async {
      //  + await _getToken();
        var fullUrl = _url + apiUrl; 
        return await http.post(
            fullUrl, 
            body: jsonEncode(data), 
            headers: _setHeaders()
        );
    }
      //  + await _getToken(); 
    getData(apiUrl) async {
       var fullUrl = _url + apiUrl; 
       return await http.get(
         fullUrl, 
         headers: _setHeaders()
       );
    }

    _setHeaders() => {
        'Content-type' : 'application/json',
        'Accept' : 'application/json',
    };

    _getToken() async {
        SharedPreferences localStorage = await SharedPreferences.getInstance();
        var token = localStorage.getString('token');
        return '?token=$token';
    }
}

view Screen 两个按钮几乎都在view screen的尽头:

import 'package:erg_app/StartScan.dart';
import 'package:erg_app/StockPage.dart';
import 'package:erg_app/Widgets/nav-drawer.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:erg_app/api/api.dart';

class detailsPage extends StatefulWidget {
  Map<String, dynamic> value;
  detailsPage({Key key, @required this.value}) : super(key: key);

  @override
  _detailsPageState createState() => _detailsPageState(value);
}

class _detailsPageState extends State<detailsPage> {
  var user;
  var userData;
  var userDetail;
  var anchors;
  var dailyStatus;
  var dailyStocks;
  @override
  void initState() {
    _getUserInfo();
    super.initState();
    _checkDailyStockTakingStatus();
  }

  void _getUserInfo() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var userJson = localStorage.getString('loginRes');
    user = json.decode(userJson);
    userDetail = user['UserDetail'];
    anchors = user['Anchors'];
    setState(() {
      userData = user;
    });
  }

  void _checkDailyStockTakingStatus() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var res = await CallApi().getData('CheckDailyStockTakingStatus?userId=${user['UserId']}&agentId=${userDetail['Oid']}');
    var body = json.decode(res.body);
    if (body['Success']) {
      dailyStatus = localStorage.setString('inventoryStatus', json.encode(body));
      // I want to use the dailyStocks to access the nested stock items in the array
      dailyStocks = dailyStatus['Stock'];
    } else {
      //   // _showMsg();
      print(Text('Something Went Wrong'));
    }
  }

  Map<String, dynamic> value;

  _detailsPageState(this.value);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: NavDrawer(),
      appBar: AppBar(
        title: Text("Anchor Details"),
        iconTheme: IconThemeData(color: Colors.white),
        backgroundColor: Colors.green,
      ),
      body: Container(
        padding: const EdgeInsets.fromLTRB(10, 30, 10, 10),
        child: ListView(
          children: <Widget>[
            Row(
              children: <Widget>[
                SizedBox(width: 15),
                Icon(Icons.home, size: 30, color: Colors.green[400]),
                SizedBox(width: 15),
                Text(
                  '${value['Acronym']} Distribution Center(s)',
                  style: TextStyle(color: Colors.green[400], fontSize: 20),
                ),
              ],
            ),
            ListView.builder(
                shrinkWrap: true,
                itemCount: value['DistributionCentres'].length,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int i) {
                  return Padding(
                    padding: const EdgeInsets.all(10.0),
                    ////////////// 1st card///////////

                    child: Card(
                      elevation: 4.0,
                      color: Colors.grey[100],
                      margin: EdgeInsets.only(
                          left: 10, right: 10, top: 20, bottom: 10),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10)),
                      child: Container(
                        padding: EdgeInsets.only(left: 15, top: 20, bottom: 10),
                        width: MediaQuery.of(context).size.width,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Container(
                                      width: 50.0,
                                      height: 50.0,
                                      decoration: new BoxDecoration(
                                          shape: BoxShape.circle,
                                          image: new DecorationImage(
                                              fit: BoxFit.cover,
                                              image: AssetImage(
                                                  'assets/images/user.png')))),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Text(
                                  value['DistributionCentres'][i]['Name'],
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    color: Color(0xFF9b9b9b),
                                    fontSize: 20,
                                    decoration: TextDecoration.none,
                                    fontWeight: FontWeight.normal,
                                  ),
                                ),
                              ],
                            ),
                            Container(width: 10),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Allocated Farmers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 70, top: 12),
                                  child: Text(
                                    '300',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Validated Farmers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 70, top: 12),
                                  child: Text(
                                    '400',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Non Validated Farmers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 40, top: 12),
                                  child: Text(
                                    '123',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Distribution Centers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 60, top: 12),
                                  child: Text(
                                    '76',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Daily Inventory Status:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 50, top: 12),
                                  child: Text(
                                    'Completed',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: 'Completed' == 'Completed'
                                          ? Colors.green
                                          : Colors.red,
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Container(
                              height: 20,
                            ),
                            Row(
                              children: <Widget>[
                                /////////// Based on the response I want to use it to control these two buttons below
                                ///if the response is 200 it should display validate farmer else it should display Take Inventory/////////////

                                Padding(
                                  padding: const EdgeInsets.all(10.0),
                                  //this is where I want to perform the check but its not working
                                  // dailyStatus['StatusCode'] == 200
                                  child: 'InCompleted' == 'Completed'
                                      ? FlatButton(
                                          child: Padding(
                                            padding: EdgeInsets.only(
                                                top: 8,
                                                bottom: 8,
                                                left: 10,
                                                right: 10),
                                            child: Text(
                                              'Validate Farmers',
                                              textDirection: TextDirection.ltr,
                                              style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 15.0,
                                                decoration: TextDecoration.none,
                                                fontWeight: FontWeight.normal,
                                              ),
                                            ),
                                          ),
                                          color: Colors.green,
                                          shape: new RoundedRectangleBorder(
                                              borderRadius:
                                                  new BorderRadius.circular(
                                                      20.0)),
                                          onPressed: () {
                                            Navigator.push(
                                                context,
                                                new MaterialPageRoute(
                                                    builder: (context) =>
                                                        StartScanPage() ));
                                            // Edit()was here
                                          },
                                        )
                                        //if the status is not 200 then it should allow an agent to take inventory
                                      : FlatButton(
                                          child: Padding(
                                            padding: EdgeInsets.only(
                                                top: 8,
                                                bottom: 8,
                                                left: 10,
                                                right: 8),
                                            child: Text(
                                              'Take Inventory',
                                              textDirection: TextDirection.ltr,
                                              style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 15.0,
                                                decoration: TextDecoration.none,
                                                fontWeight: FontWeight.normal,
                                              ),
                                            ),
                                          ),
                                          color: Colors.blueGrey,
                                          shape: new RoundedRectangleBorder(
                                              borderRadius:
                                                  new BorderRadius.circular(
                                                      20.0)),
                                          onPressed: () {
                                            Navigator.push(
                                                context,
                                                new MaterialPageRoute(
                                                    builder: (context) =>
                                                        StockInventoryPage() ));
                                          },
                                        ),
                                ),

                                /////////// End of Buttons /////////////
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                })
          ],
        ),
      ),
    );
  }
}

我也试过了,但还是不行,求帮助:


  void _checkDailyStockTakingStatus() async {
    try {
      final queryParameters = {
        'userId': 'b6caf34c-a425-4710-a3ee-aa22a382882a',
        'agentId': '57',
      };
      // SharedPreferences localStorage = await SharedPreferences.getInstance();
      // var res = await CallApi().getData('CheckDailyStockTakingStatus? 
      // userId=${user['UserId']}&agentId=${userDetail['Oid']}');

      final uri = Uri.http('http://api.ergagro.com:112/',
          'CheckDailyStockTakingStatus?', queryParameters);

      print("FullUrl");
      print(uri);
      var res = await get(uri, headers: {'Content-Type': 'application/json'});
        var body = json.decode(res.body);

        print(body[0]);
      

      // var status = localStorage.setString('inventoryStatus', 
      //json.encode(body));
      // setState(() {
      //   dailyStatus = status;
      // });
    } catch (e) {
      print(Text('Error Occured: $e'));
    }
  }

错误信息

【问题讨论】:

  • 如果您可以分享正在返回的响应将会很有帮助。
  • 在邮递员上它返回 200 但在屏幕上它确实返回任何东西请你帮我吗?这是网址:api.ergagro.com:112/…
  • 如果我尝试访问它显示的任何值:该方法在 null 上调用
  • 您提供的网址返回服务器错误 500。
  • 好的,请往这边走:api.ergagro.com:112 然后选择:CheckDailyStockTakingStatus 并使用我提供的 userId 和 agent Id 作为参数

标签: flutter dart flutter-layout flutter-dependencies dart-http


【解决方案1】:

将 uri 更改为:

final uri = Uri.http('api.ergagro.com:112','/CheckDailyStockTakingStatus', queryParameters);

还有setState获取数据后重建小部件:

setState(() {
  dailyStocks = dailyStatus['Stock'];
});

【讨论】:

    【解决方案2】:

    修改State中的变量后需要使用setState。 例如。

      void _checkDailyStockTakingStatus() async {
        SharedPreferences localStorage = await SharedPreferences.getInstance();
        var res = await CallApi().getData('CheckDailyStockTakingStatus?userId=${user['UserId']}&agentId=${userDetail['Oid']}');
        var body = json.decode(res.body);
        if (body['Success']) {
          var status= localStorage.setString('inventoryStatus', json.encode(body));
          // I want to use the dailyStocks to access the nested stock items in the array
          var stocks= status['Stock'];
          setState((){
             dailyStatus = status;
             dailyStocks = stocks;
          });
        } else {
          //   // _showMsg();
          print(Text('Something Went Wrong'));
        }
      }
    
    

    https://flutter.dev/docs/development/ui/interactive

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 2018-12-18
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多