简体   繁体   English

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

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

So , My flutter App doesn't show content that is fetched through an API unless some button is pressed then it shows only, I don't know what the problem is here but it is quite annoying, I don't know what is causing hence below is my entire code, I am new to flutter so sorry if it is some stupid mistake.所以,除非按下某个按钮,否则我的 flutter App 不会显示通过 API 获取的内容,然后它只显示,我不知道这里的问题是什么,但很烦人,我不知道是什么原因造成的因此,下面是我的整个代码,如果这是一些愚蠢的错误,我是新手,所以很抱歉。 Thank you.谢谢你。

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,
  ),
  );
 }
}

Replace this:替换这个:

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

With this:有了这个:

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

this is because your UI has a state and the statues has to be changed when the data is retrieved.这是因为您的 UI 具有状态,并且在检索数据时必须更改状态。 The app doesn't know it has to rebuild itself.该应用程序不知道它必须重建自己。 The rebuilding is happening when the button is being pressed.当按下按钮时,正在重建。

A better approach to this would be to use a FutureBuilder and pass the future, that is the data recieved to the FutureBuilder, to render it.一个更好的方法是使用 FutureBuilder 并传递未来,即接收到 FutureBuilder 的数据,以呈现它。

Show a circular progress indicator when the data is not yet ready and display the data when it is.当数据尚未准备好时显示循环进度指示器,并在数据准备好时显示数据。 Look into the isBusy property of the FutureBuilder for this.为此,请查看 FutureBuilder 的 isBusy 属性。

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

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