flutter 进度指示器的抖动状态不变[重复]

kuuvgm7e  于 2023-03-04  发布在  Flutter
关注(0)|答案(3)|浏览(159)
    • 此问题在此处已有答案**:

What is a Future and how do I use it?(6个答案)
两年前关闭了。
我正在尝试解析flutter中的api。异步请求延迟了进度指示器显示的响应。但是进度指示器在获取响应后并没有消失。它仍然在屏幕上。
如何改变状态的进程加载程序到listview.builder当响应被提取?
这是我的准则。

import 'dart:convert';

    import 'package:flutter/material.dart';

    import 'users.dart';
    import 'package:http/http.dart' as http;

    class HomePage extends StatefulWidget {
     @override
     _HomePageState createState() => _HomePageState();
    }

    class _HomePageState extends State<HomePage> {

    bool isLoading = false;

    List<Users> _users;
    Future<List<Users>> getUsers() async {
    var response = await http.get(Uri.encodeFull('http://jsonplaceholder.typicode.com/users'));
    _users = usersFromJson(response.body);
    isLoading = true;

  }
  @override
  void initState() {
      setState(() {
        getUsers();
      });
  }

    @override
    Widget build(BuildContext context) {
     return Scaffold(
      appBar: AppBar(
       title: Text(isLoading ? "Parsed Json" : "Loading..."),
       backgroundColor: Colors.deepPurple,
      ),
       body: isLoading ? ListView.builder(
             itemCount: _users.length,
             itemBuilder: (BuildContext context,int index){
            return ListTile(
              leading: Image.network('https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80'),
              title:  Text(_users[index].name),
             );
         }) : Center(child: CircularProgressIndicator()),
        );
     }
    }
ldfqzlk8

ldfqzlk81#

工作代码,试试这个

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isLoading = false;

  List<Users> _userList = [];

  Future<void> getUsers() async {
    isLoading = true;
    var response = await http
        .get(Uri.encodeFull('http://jsonplaceholder.typicode.com/users'));
    var jsonResponse = jsonDecode(response.body);
    // print(jsonResponse);
    jsonResponse.forEach((data) {
      Users user = Users.fromMap(data);
      print(user);
      _userList.add(user);
    });
    isLoading = false;
  }

  @override
  void initState() {
    getUsers().then((value) => setState(() {}));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(isLoading ? "Loading..." : "Parsed Json"),
          backgroundColor: Colors.deepPurple,
        ),
        body: isLoading
            ? Center(child: CircularProgressIndicator())
            : ListView.builder(
                itemCount: _userList.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(_userList[index].name),
                  );
                }));
  }
}

class Users {
  int id;
  String name;
  String username;
  Users({
    this.id,
    this.name,
    this.username,
  });
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'username': username,
    };
  }

  factory Users.fromMap(Map<String, dynamic> map) {
    if (map == null) return null;

    return Users(
      id: map['id'],
      name: map['name'],
      username: map['username'],
    );
  }

  String toJson() => json.encode(toMap());

  factory Users.fromJson(String source) => Users.fromMap(json.decode(source));

  @override
  String toString() => 'Users(id: $id, name: $name, username: $username)';
}
bmvo0sr5

bmvo0sr52#

选中您的_user != null而不是bool,否则显示列表指示符

qyyhg6bp

qyyhg6bp3#

**void initState()**方法当这个对象被插入到树中时调用。框架将为它创建的每个State对象调用这个方法一次。所以在initState()方法中不需要setState。

尝试在响应后设置setState,因此

@override
  void initState() {
    super.initState();
      getUsers();

  }


 Future<List<Users>> getUsers() async {
    isLoading = false;
    var response = await http.get(Uri.encodeFull('http://jsonplaceholder.typicode.com/users'));
    _users = usersFromJson(response.body);
    print(_users);
    setState(() {
      isLoading = true;
    });

    return _users;
  }

相关问题