繁体   English   中英

除非单击某个按钮,否则 Flutter App 不会显示内容

[英]Flutter App doesn't show content unless some button is clicked

所以,除非按下某个按钮,否则我的 flutter App 不会显示通过 API 获取的内容,然后它只显示,我不知道这里的问题是什么,但很烦人,我不知道是什么原因造成的因此,下面是我的整个代码,如果这是一些愚蠢的错误,我是新手,所以很抱歉。 谢谢你。

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:FotoApp/image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

final Color myColor = Color(0xff222f3e);
final Color myColor2 = Color(0xff2f3640);

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 await FlutterDownloader.initialize(debug: true);
 runApp(
  MyApp(),
 );
}

 class MyApp extends StatefulWidget {
 @override
  _MyAppState createState() => _MyAppState();
 }

 class _MyAppState extends State<MyApp> {
 static String query = "wallpapers";
 List<dynamic> wallpapersList;
 Icon searchIcon = Icon(Icons.search);
 Widget searchBar = Text("FotoApp");

  @override
 void initState() {
  super.initState();
  initialize();
  }

 void initialize() async {
var apiUrl =
    "https://api.pexels.com/v1/search?query=" + query + "&per_page=500";
http.Response response = await http.get(
  apiUrl,
  headers: {
    HttpHeaders.authorizationHeader:
        "563492ad6f91700001000001999da5bd71d04ece9af9ba1a03e8beaf"
  },
);
print(apiUrl);
if (response.statusCode == 200) {
  try {
    final responseJson = jsonDecode(response.body);
    wallpapersList = responseJson['photos'];
  } catch (e) {
    print(e);
  }
} else
  print(response.reasonPhrase);
}

@override
Widget build(BuildContext context) {
var tabindex = 0;

return MaterialApp(
  debugShowCheckedModeBanner: false,
  home: Scaffold(
    appBar: AppBar(
      title: searchBar,
      backgroundColor: myColor,
      actions: [
        IconButton(
          icon: searchIcon,
          onPressed: () {
            setState(() {
              if (this.searchIcon.icon == Icons.search) {
                this.searchIcon = Icon(Icons.cancel);
                this.searchBar = TextField(
                  textInputAction: TextInputAction.go,
                  style: TextStyle(color: Colors.white),
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "Search",
                      hintStyle: TextStyle(color: Colors.white)),
                  onSubmitted: (value) {
                    query = value;
                    initialize();
                    print(query);
                  },
                );
              } else {
                this.searchIcon = Icon(Icons.search);
                this.searchBar = Text("FotoApp");
              }
            });
          },
          color: Colors.white,
        )
      ],
    ),
    body: wallpapersList != null
        ? StaggeredGridView.countBuilder(
            padding: const EdgeInsets.all(8.0),
            crossAxisCount: 4,
            itemBuilder: (BuildContext context, int index) {
              String imgPath = wallpapersList[index]["src"]["large"];
              return Card(
                child: InkWell(
                  onTap: () => Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ImagePath(imgPath))),
                  child: Hero(
                      tag: imgPath,
                      child: FadeInImage(
                        width: MediaQuery.of(context).size.width,
                        placeholder: AssetImage("assets/loading.gif"),
                        image: NetworkImage(imgPath),
                        fit: BoxFit.cover,
                      )),
                ),
              );
            },
            staggeredTileBuilder: (index) =>
                StaggeredTile.count(2, index.isEven ? 2 : 3),
            itemCount: wallpapersList.length,
          )
        : Center(
            child: CircularProgressIndicator(
              backgroundColor: Colors.white,
            ),
          ),
    bottomNavigationBar: BottomNavigationBar(
      backgroundColor: Colors.black,
      selectedItemColor: Colors.black,
      unselectedItemColor: Colors.grey,
      currentIndex: tabindex,
      type: BottomNavigationBarType.shifting,
      items: [
        BottomNavigationBarItem(
            icon: Icon(Icons.image), title: Text("Wallpapers")),
        BottomNavigationBarItem(
            icon: Icon(Icons.view_list), title: Text("Categories")),
        BottomNavigationBarItem(
            icon: Icon(Icons.info), title: Text("About"))
      ],
    ),
    backgroundColor: myColor2,
  ),
  );
 }
}

替换这个:

try {
  final responseJson = jsonDecode(response.body);
  wallpapersList = responseJson['photos'];
} catch (e) {
  print(e);
}

有了这个:

try {
  final responseJson = jsonDecode(response.body);
  setState(() {
    wallpapersList = responseJson['photos'];
  });      
} catch (e) {
  print(e);
}

这是因为您的 UI 具有状态,并且在检索数据时必须更改状态。 该应用程序不知道它必须重建自己。 当按下按钮时,正在重建。

一个更好的方法是使用 FutureBuilder 并传递未来,即接收到 FutureBuilder 的数据,以呈现它。

当数据尚未准备好时显示循环进度指示器,并在数据准备好时显示数据。 为此,请查看 FutureBuilder 的 isBusy 属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM