首页 > 解决方案 > 为什么 Builder 卡在进度加载器上?

问题描述

我已经做了几个小时了,没有任何解决方案可以解决上传并单击按钮继续后导致我的应用程序卡住的原因。

在添加房屋图像屏幕中,只有上传按钮和添加图像,每一个都从特定的 API 端点加载数据。问题是,添加我的照片然后点击上传后,整个屏幕卡在进度条上!..我调试和搜索了很多,但找不到真正的原因。

    var _status = true;
var _uploadStatus = false;
var _isImageSelected = false;

class AddImages extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MultiImage(),
    );
  }
}

void createRecord(context) async {
  var address = {
    'locality': _locality,
    'city': _city,
    'state': _state,
    'society': _address,
    'pincode': _pincod,
    'houseNo': _hono
  };
  var overview = {
    'bathroom': _bath,
    'room': _beds,
    'furnishingStatus': _farnistatus,
    'propertyType': _propert,
    'preferedType': _preferedType
  };
  ref = await databaseReference.collection("House")
  // .document("1")
      .add({
    'Address': address,
    'Date Created': DateTime.now(),
    'Date Updated': DateTime.now(),
    'Facilities': _filters,
    'Overview': overview,
    'favourite': 0,
    'houseImages': imageDataPath,
    'builtUpArea': _buildup,
    'depositAmount': _deposit,
    'description': _detail,
    'monthlyRent': _monthly,
    'ownerDetail': '/User/' + userReference.toString(),
    'status': 'Available'
  });
  print(ref!.id);
  Navigator.pop(context);
  Navigator.pop(context);
  Fluttertoast.showToast(msg: 'House Ad Posted Successfully');
  Navigator.pushReplacement(
      context, MaterialPageRoute(builder: (_) => SearchPage()));
}

class Choice {
  const Choice({required this.title, required this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'Upload', icon: Icons.cloud_upload),
  const Choice(title: 'Post House Deal', icon: Icons.check)
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({Key? key, required this.choice}) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    final TextStyle? textStyle = Theme.of(context).textTheme.display1;
    return Card(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(choice.icon, size: 128.0, color: textStyle!.color),
            Text(choice.title, style: textStyle),
          ],
        ),
      ),
    );
  }
}

class MultiImage extends StatefulWidget {
  @override
  _MultiImageState createState() => new _MultiImageState();
}

class _MultiImageState extends State<MultiImage> {
  List<Asset> images = <Asset>[];
  List<String> imagePaths = <String>[];
  String error = 'No Error Detected';

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

  String? filePath;

  Widget buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }
  List<String> imageDataPath = <String>[];
  late int i=0,len;
  Future<Null> _addImages(var pic) async {
    var t = await pic.filePath;
    File file=new File(t);
    filePath = '${DateTime.now()}.png';
    FirebaseStorage storage = FirebaseStorage.instance;
    Reference ref = storage.refFromURL('gs://cloud-keja.appspot.com/').child(filePath!);
    UploadTask task = ref.putFile(file);
    TaskSnapshot storageTaskSnapshot = await task.whenComplete(() => null);
    String url = await storageTaskSnapshot.ref.getDownloadURL();

    print("\nUploaded: "+url);
    //Download URL's
    setState((){
      imageDataPath.add(url);
      i++;
    });
    if(len==i){
      setState(() {
        _status=!_status;
        _uploadStatus=!_uploadStatus;
        print('Upload State Changed');
      });
    }
  }


  //Uploading images
  Future<Null> _uploadImages() async {
    setState(() {
      len = images.length;
      _uploadStatus = !_uploadStatus;
    });
    images.forEach((pic) {
      _addImages(pic);
    });
  }

  Future<void> loadAssets() async {
    List<Asset> resultList = <Asset>[];
    String error = 'No Error Detected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 300,
        enableCamera: true,
        selectedAssets: images,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#1972d2",
          actionBarTitle: "Select Images",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );

      for (var r in resultList) {
        var t = await r.name;
        print(t);
      }
      if (resultList.isNotEmpty) {
        setState(() {
          _isImageSelected = true;
        });
      } else {
        setState(() {
          _isImageSelected = false;
        });
      }
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      images = resultList;
      error = error;
    });
  }
  var complete=0;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      home: new Scaffold(
        appBar: AppBar(
          title: Text("Add House Images"),
          backgroundColor: Colors.blue[700],
          actions: _isImageSelected
              ? <Widget>[
            // action button
            _status
                ? IconButton(
              icon: Icon(choices[0].icon),
              onPressed: () {
                _uploadImages();
              },
            )
                : IconButton(
              icon: Icon(choices[1].icon),
              onPressed: () async {
                print('Saved');
                createRecord(context);
                await FirebaseFirestore.instance.collection('House').doc();
                Fluttertoast.showToast(msg: 'House Ad Posted Successfully');
                Navigator.pushReplacement(
                    context, MaterialPageRoute(builder: (_) => SearchPage()));
                //upload code here here
              },
            ),
          ]
              : null,
        ),
        body: _uploadStatus
            ? Center(child: new CircularProgressIndicator())
            : new Column(
          children: <Widget>[
            Expanded(
              child: buildGridView(),
            ),
          ],
        ),
        floatingActionButton: _status
            ? FloatingActionButton(
          onPressed: () {
            loadAssets();
          },
          child: Icon(Icons.add_a_photo),
          backgroundColor: Colors.blue[700],
        )
            : null,
      ),
    );
  }
}

标签: flutterdart

解决方案


推荐阅读