Dya*_*ary 17 crash image dart flutter
我已经构建了一个足够复杂的 flutter 应用程序,在我开始从位于 AWS 上的 api 获取图像之前,一切都运行良好。但是在使用实际数据填充 image.network 小部件和 cached_network_image 后,我开始随机出现大量崩溃,并且在导航到其他包含图像的页面时出现更多崩溃。
Flutter 没有向我显示任何错误,仅显示“与设备的连接丢失”。
我正在 android 和 iOS 设备上测试这个应用程序,它是一样的:很多崩溃。
每个图像的大小约为 200-400 KB,但即使我在屏幕上显示其中 6 个图像,也会发生崩溃。
起初我不知道崩溃是由图像引起的,所以我尝试了很多方法并更改了很多代码。就像使我的大多数小部件无状态一样,尝试将 Cached_Network_Image 更改为 Image.Network 小部件,使小部件变小,以便在处于设置状态时重建不会占用大量内存。我还尝试使用 devTools 来诊断问题以了解 veil。
devTools 仅在应用程序崩溃之前显示内存激增。
我现在确定这些图像是导致这些崩溃的原因。
这是 main.js 中的代码,不包括 import ,但如果需要,我很乐意提供。
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await allTranslations.init();
User user = await getLocalUserObject();
runApp(Bestiee(user));
}
class Bestiee extends StatefulWidget {
User user;
Bestiee(this.user);
@override
_BestieeState createState() => _BestieeState();
}
class _BestieeState extends State<Bestiee> {
SpecificLocalizationDelegate _localeOverrideDelegate;
String currentLocal = "en";
Widget startScreen;
GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
@override
void initState() {
bypassLogin();
_localeOverrideDelegate = new SpecificLocalizationDelegate(null);
applic.onLocaleChanged = onLocaleChange;
NotificationHandler.scaffoldKey = scaffoldKey;
new NotificationHandler().initializeFcmNotification();
super.initState();
// allTranslations.onLocaleChangedCallback = _onLocaleChanged;
}
@override
Widget build(BuildContext context) {
print('-------------------------------------------');
print('main is called');
return MaterialApp(
localizationsDelegates: [
_localeOverrideDelegate,
const TranslationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
// GlobalCupertinoLocalizations.delegate,
],
supportedLocales: applic.supportedLocales(),
// locale: Locale("en", "UK"),
// locale: Locale("fa", "IR"),
// locale : Locale(allTranslations.currentLanguage),
locale: Locale(currentLocal),
// home: WelcomScreen(changeLanguageCallBack: changeLanguageCallBack,),
home: Scaffold(
key: scaffoldKey,
body: QuickActionsManager(
child: startScreen,
),
),
routes: {
ItemSearchResultScreen.id: (context) =>
ItemSearchResultScreen(screenName: 'Items'),
ItemSearchResultScreen.usedItemsId: (context) =>
ItemSearchResultScreen(screenName: 'Used Items'),
PlacesSearchResultScreen.id: (context) =>
}
Run Code Online (Sandbox Code Playgroud)
... 20 更多其他路线
HotScreen.dart 在其中大多数崩溃发生在从和导航到其他路线时:
class HotScreen extends StatefulWidget {
static List<Category> categories = [];
static List<Subcategory> subcategories = [];
static User user = User();
static Location userLocation = Location();
static List<Item> items ;
static List<Item> usedItems;
static List<Place> places;
static List<Person> people ;
@override
_HotScreenState createState() => _HotScreenState();
}
class _HotScreenState extends State<HotScreen> {
@override
void initState() {
HotScreen.items = [];
HotScreen.usedItems = [];
HotScreen.places = [];
HotScreen.people = [];
getItemPlacesPeople();
getAllCategories();
getAllSubcategories();
super.initState();
}
@override
Widget build(BuildContext context) {
print('hot screen called');
SingleItemScreen.isScreenCalledFromAddUsedItemScreen = false;
return Scaffold(
body: ModalProgressHUD(
inAsyncCall: false,
child: Container(
decoration: kPageMainBackgroundColorBoxDecoration,
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
//main screen scrollable widgets
child: ListView(
shrinkWrap: true,
children: <Widget>[
Text(
getTranslation('Bazzar24', context),
style: kBazarGalleryTitleStyle,
),
FeaturedItems(isScreenCalledFromMyPropertiesScreen: false),
FeaturedUsedItems(),
FeaturedIPlaces(isCalledFromMyPropertiesScreen: false),
FeaturedPeople(isCalledFromMyPropertiesScreen: false),
// NewPlaces(
// places: places,
// ),
],
),
),
),
),
),
);
}
getAllCategories() async {
List<Category> _categories = [];
http.Response response = await getRequest(baseURL + plainCategoryAPI);
var allCategoriesMap = jsonDecode(response.body);
for (int i = 0; i < allCategoriesMap.length; i++) {
var json = allCategoriesMap[i];
Category category = Category.fromJson(json);
category.id = allCategoriesMap[i]['_id'];
//NOTE here I have used SueperCategory instead of camelCase superCategory because the data is already saved in this way
category.superCategory = allCategoriesMap[i]['SuperCategory'];
_categories.add(category);
}
HotScreen.categories.clear();
HotScreen.categories.addAll(_categories);
allCategoriesMap.clear();
}
getAllSubcategories() async {
List<Subcategory> _subcategories = [];
http.Response response = await getRequest(baseURL + plainSubcategoryAPI);
var allSubcategoriesMap = jsonDecode(response.body);
for (int i = 0; i < allSubcategoriesMap.length; i++) {
var json = allSubcategoriesMap[i];
Subcategory subcategory = Subcategory.fromJson(json);
subcategory.id = allSubcategoriesMap[i]['_id'];
_subcategories.add(subcategory);
}
HotScreen.subcategories.clear();
HotScreen.subcategories.addAll(_subcategories);
allSubcategoriesMap.clear();
}
getItemPlacesPeople() async {
await getAllItems(setItemsAndUsedItemsStateCallback);
await getAllPlaces(setPlaceStateCallback);
await getAllPeople(setPeopleStateCallback);
}
setItemsAndUsedItemsStateCallback(List<List<Item>> items){
if(this.mounted){
setState(() {
HotScreen.items.clear();
HotScreen.usedItems.clear();
HotScreen.items.addAll(items[0]);
HotScreen.usedItems.addAll(items[1]);
});
}
}
setPlaceStateCallback(List<Place> places){
if(this.mounted){
setState(() {
HotScreen.places.clear();
HotScreen.places.addAll(places);
});
}
}
setPeopleStateCallback(List<Person> people){
if(this.mounted){
setState(() {
HotScreen.people.clear();
HotScreen.people.addAll(people);
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
HotScreen 中的示例小部件:
FeaturedItems.dart :
class FeaturedItems extends StatelessWidget {
FeaturedItems({this.isScreenCalledFromMyPropertiesScreen});
final bool isScreenCalledFromMyPropertiesScreen;
final List<Item> items = HotScreen.items;
final myUsedItems = MyPlacesJobsItems.items;
@override
Widget build(BuildContext context) {
print('featured items widget called');
List<Item> _items;
if (isScreenCalledFromMyPropertiesScreen == true) {
_items = items;
} else {
_items = myUsedItems;
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20,
),
Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Text(
isScreenCalledFromMyPropertiesScreen
? 'My Items'
: 'Featured Items',
style: kFeatureTitleTextStyle),
),
),
Container(
height: 700 / 3.5,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: items.length < 10 ? HotScreen.items.length : 10,
itemBuilder: (contet, int index) {
return SingleItemCard(
item: _items.length > 10
? HotScreen.items[_items.length - 10 + index]
: HotScreen.items[index],
isPersonItem: false,
moduleName: _items.length > 10
? HotScreen.items[_items.length - 10 + index].moduleName
: HotScreen.items[index].moduleName,
isScreenCalledFromMyPropertiesScreen:
isScreenCalledFromMyPropertiesScreen,
);
},
),
),
SizedBox(
height: 10,
),
//more button
Visibility(
visible: !isScreenCalledFromMyPropertiesScreen,
child: Align(
alignment: Alignment.topLeft,
child: Container(
width: 80,
height: 30,
child: SmallRoundMoreButton(onPressed: () {
Navigator.pushNamed(context, MoreHotItemsScreen.id);
}),
),
),
),
SizedBox(
height: 20,
),
],
);
}
}
Run Code Online (Sandbox Code Playgroud)
以及在从 HotScreen.dart 来回切换时导致随机崩溃的示例页面。
这是 SinglePlaceScreen.dart :
class SinglePlaceScreen extends StatelessWidget {
SinglePlaceScreen(
{this.place, this.isScreenCalledFromOwnerSelfRegistrationScreen = false});
static const id = 'singlePlaceScreen';
final Place place;
final bool isScreenCalledFromOwnerSelfRegistrationScreen;
final PageController pageController = PageController(initialPage: 2);
final int activePageInt = 0;
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
double getSocialMediaScreenSize() {
SocialMedia socialMedia = place.socialMedia;
double requiredScreenSpace = 0;
if (socialMedia.facebook != '') requiredScreenSpace += 140;
if (socialMedia.instagram != '') requiredScreenSpace += 140;
if (socialMedia.twitter != '') requiredScreenSpace += 140;
if (socialMedia.googlePlus != '') requiredScreenSpace += 140;
if (socialMedia.pinterest != '') requiredScreenSpace += 140;
if (socialMedia.youTube != '') requiredScreenSpace += 140;
if (socialMedia.snapChat != '') requiredScreenSpace += 140;
return requiredScreenSpace;
}
@override
Widget build(BuildContext context) {
double screenWith = MediaQuery.of(context).size.width - 30;
print('single place screen called');
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: Text(place.name),
),
body: Container(
decoration: kPageMainBackgroundColorBoxDecoration,
child: ListView(
shrinkWrap: true,
children: <Widget>[
//column for upper button and image sections and lower comments sections
Column(
children: <Widget>[
//stack for the top image components and the middle buttons component
Stack(
alignment: Alignment.topCenter,
children: <Widget>[
TopWidgets(
place,
isScreenCalledFromOwnerSelfRegistrationScreen,
getSocialMediaScreenSize,
scaffoldKey),
//middle buttons section
Positioned(
top: 230,
child: Container(
decoration: kAppSingleItemScreenMainCardsBoxDecoration,
width: screenWith,
height: 1000 +
((place.description.length / 100) * 30) +
(place.tags.length * 5) +
getSocialMediaScreenSize(),
child: Column(
children: <Widget>[
ItemNameCircleRaterWidget(
name: place.name,
isScreenCalledFromOwnerSelfRegistrationScreen:
isScreenCalledFromOwnerSelfRegistrationScreen,
),
//tags header
TagsWidget(
tags: place.tags,
),
//descriptions header
DescriptionWidget(
description: place.address,
headerText: 'Adress',
),
DescriptionWidget(
headerText: 'Description',
description: place.description,
),
//phone number buttons
FittedBox(
child: Container(
height: 130,
child: Row(
children: <Widget>[
PhoneNumberNumberWidgets(
phoneNumbers: place.phoneNumbers,
),
PhoneNumberOwnerWidgets(
ownerOne: place.phoneNumbers[0].owner,
ownerTow: place.phoneNumbers[1].owner,
),
],
),
),
),
// Container(
// height: 300,
// child: MyGoogleMaps(place.location, place.name, isScreenCalledFromOwnerSelfRegistrationScreen),
// ),
ServicesWidget(
scaffoldKey: scaffoldKey,
services: place.services,
),
//social media section
SocialMediaWidgets(
place: place,
),
],
),
),
)
],
),
//top tow albums Sections
Albums(
place: place,
),
//lower comments section
Comments(
place: place,
),
SizedBox(
height: 30,
),
// done button
Visibility(
visible: place != null,
child: DoneButton(
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
(Route<dynamic> r) => false);
},
),
)
],
)
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望应用程序不会崩溃,因为我没有使用那么多图像(6 个 200 KB 的图像)。
当它崩溃时,只有“与设备的连接丢失”显示为错误;
任何帮助是赞赏的家伙。谢谢。
对于长图像列表或网格,我使用 Image.network 和合理的 cacheHeight 和 cacheWidth 参数(大约 200 +/-)。这为我解决了内存增加问题。否则我还没有找到使用 cachedimage 的解决方案。如果图像很大(大又名 jpg,每个 2 Mb),如果我们为它提供偶数 10 个奇数元素的列表,即使教程中最简单的缓存网络图像示例代码也不起作用。内存立即变为 3-4-500Mb,然后我们出现内存不足错误。
但另一个问题是,Image.network 没有很好的错误处理。
| 归档时间: |
|
| 查看次数: |
2560 次 |
| 最近记录: |