флаттер-сетка - PullRequest
       15

флаттер-сетка

0 голосов
/ 10 ноября 2019

Я хотел бы отобразить виджет, которому требуется HTTP-вызов для получения некоторых данных.

Моя проблема заключается в том, что данные не меняются и по-прежнему получают нулевое значение

, когда я помещаю некоторые журналы, явидеть, что HTTP-вызов завершен, и вызывается метод setState (), но виджет не обновляется

Я новичок в трепетании. Я пришел из реагировать нативно. Есть ли такой метод, как componentWillMount, поэтому вызов HTTP перед виджетомэто мой код

import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import './login.dart';


class Developer extends StatefulWidget {
  @override
  _DeveloperState createState() => _DeveloperState();
}

class _DeveloperState extends State<Developer> {
  bool _isLoading = false;
  SharedPreferences sharedPreferences;

  void getJsonData() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    Map data = {'sale_id': sharedPreferences.getInt("token")};

    var jsonResponse;

    if (!_isLoading) {
      setState(() {
        _isLoading = true;
      });
      var response = await http.post(
        "url",
        body: json.encode(data),
        headers: {
          "Content-Type": "application/json",
          HttpHeaders.authorizationHeader: 'Basic YnJva2VyOmJyb2tlcl8xMjM='
        },
      );

      if (response.statusCode == 200) {
        jsonResponse = json.decode(response.body);
        print('jsonRespnse');
        print(jsonResponse['developer_list']);
        if (jsonResponse != null) {
          setState(() {
            data['developer_list'] = jsonResponse['developer_list'];
            _isLoading = false;
          });

          sharedPreferences.setString("token", jsonResponse['sale_id']);
        }
      } else {
        setState(() {
          _isLoading = true;
        });
        print(response.body);
      }
    }
  }

  var data;
  @override
  void initState() {
    this.getJsonData();
    super.initState();
    checkLoginStatus();
    getJsonData();
  }

  checkLoginStatus() async {
    sharedPreferences = await SharedPreferences.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xff242426),
          title: Text("Developer", style: TextStyle(color: Colors.white)),
          actions: <Widget>[
            FlatButton(
              onPressed: () {
                sharedPreferences.clear();
                sharedPreferences.commit();
                Navigator.of(context).pushAndRemoveUntil(
                    MaterialPageRoute(
                        builder: (BuildContext context) => LoginPage()),
                    (Route<dynamic> route) => false);
              },
              child: Text("Log Out", style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
        body: Container(
          color: Colors.black,
          child: _isLoading
              ? Center(child: CircularProgressIndicator())
              : GridView.count(
                  crossAxisCount: 3,
                  children: List.generate(
                      data == null ? 0 : data['developer_list'].length,
                      (index) {
                    return Container(
                      color: Colors.black,
                      margin: EdgeInsets.all(10),
                      child: Column(
                        children: <Widget>[
                          Container(
                            width: double.infinity,
                            height: 160,
                            alignment: Alignment.center,
                            child: Image.network(
                                data['developer_list'][index]
                                    ['developer_image'],
                                width: double.infinity),
                          ),
                          Container(
                            color: Color(0x66bbbbbb),
                            width: double.infinity,
                            height: 60,
                            alignment: Alignment.center,
                            child: Text(data['developer_list'][index]
                                ['developer_name']),
                          )
                        ],
                      ),
                    );
                  }).toList()),
        ));
  }
}


Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...