gpt4 book ai didi

api - 没有互联网时 Flutter 崩溃

转载 作者:行者123 更新时间:2023-12-05 06:20:39 25 4
gpt4 key购买 nike

我的应用程序(从字面上取自 here)在我禁用互联网连接时崩溃,就像互联网的魅力一样。我怎样才能仍然能够访问该页面,显示上次访问的结果而不会卡住?我拥有 list 中包含的所有互联网许可。

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

这是代码

import 'dart:async';
import 'dart:convert';

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

Future<Album> fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/1');

if (response.statusCode == 200) {
// If the server did return a 200 OK response, then parse the JSON.
return Album.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response, then throw an exception.
throw Exception('Failed to load album');
}
}

class Album {
final int userId;
final int id;
final String title;

Album({this.userId, this.id, this.title});

factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}

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

class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
Future<Album> futureAlbum;

@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}

// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}

谢谢

最佳答案

您可以使用 connectivity library监听 wifi 状态

import 'package:connectivity/connectivity.dart';

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

subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Got a new connectivity status!
})
}

// Be sure to cancel subscription after you are done
@override
dispose() {
super.dispose();

subscription.cancel();
}

关于api - 没有互联网时 Flutter 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60364643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com