简体   繁体   中英

FutureBuilder works fine on the debug stage but on apk build always throws error

I have the following code which should show a process indicator during the process of fetching a JSON data from the web. It works fine when I run in the debug mode. But as soon as I make it to an apk, the app opens and with no time delays, it throws this error:

SocketException:

How to get rid of these issues?

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Quize It Up'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    getCategories();
  }

  Future<List> getCategories() async {
    var url = 'https://opentdb.com/api_category.php';
    var response = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});

    var jsonResponse = convert.jsonDecode(response.body);
    List categories = jsonResponse["trivia_categories"];

    return categories;
  }

  Widget mainGui() {
    return Container(
        child: FutureBuilder(
            future: getCategories(),
            builder: (BuildContext context, AsyncSnapshot<List> asyncSnapshot) {
              switch (asyncSnapshot.connectionState) {
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ConnectionState.none:
                  return RaisedButton(
                    onPressed: () => getCategories(),
                  );
                case ConnectionState.done:
                  if (asyncSnapshot.hasData)
                    return Text(asyncSnapshot.error.toString());
                  else
                    return ListView.builder(
                      itemCount: asyncSnapshot.data.length,
                      itemBuilder: (context, int index) {
                        return ListTile(
                          title: Text(asyncSnapshot.data[index]['name']),
                        );
                      },
                    );
              }
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: mainGui(),
      ),
    );
  }
}

First of all you are calling getCategories(); in your initState() method for no reason. Since getCategories() is simply building and returning a Future that you don't use in initState this call is irrelevant. You might simply delete this line or even the entire initState() method.

Then this code basically does nothing:

case ConnectionState.none:
   return RaisedButton(
      onPressed: () => getCategories(),
   );

In order to show a button that reloads the Future you might instead refresh the state like this. This will rebuild your widget and therefore rebuild the future.

case ConnectionState.none:
   return RaisedButton(
      onPressed: () {
         setState(() {});
      },
   );

But anyways. If all that you want to achieve is a loading indicator while the Future is loading I'd rather observe the hasData attribute of the snapshot. Something like this might work:

return FutureBuilder (
        future: getCategories(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data) {
              return ListView.builder(
                itemCount: asyncSnapshot.data.length,
                itemBuilder: (context, int index) {
                  return ListTile(
                    title: Text(asyncSnapshot.data[index]['name']),
                  );
                },
              );
            }
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        }
    );

Just for clarity. The error you are seeing is coming from this bug here:

case ConnectionState.done:
   if (asyncSnapshot.hasData)
      return Text(asyncSnapshot.error.toString());

Your saying here that if the Future is done and has some data received then you show the error instead of the data.

The solution was to add
<uses-permission android:name="android.permission.INTERNET"/>

in the manifest.xml file as the latest flutter SDK has changed the project structure.

是的,解决方案是添加<uses-permission android:name="android.permission.INTERNET"/> ,但您必须将其添加到 Flutter 项目中 /android/src/main 位置的 AndroidManifest.xml 文件中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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