Search code examples
flutterdartshake

Why this shake functionality not working in flutter?


This ShakePlugin is not working with this piece of code,when im just using this code without these api calls and all its working fine.

class MyAppState extends State<MyApp> {
  List data;
  String _search = 'nature';
  int index = 0;
  File imageFile;
  String imageData;
  bool dataLoaded;
  var path;
  int count = 10;
  FlutterShakePlugin _shakePlugin;
  void initState() {
    super.initState();
    _shakePlugin = FlutterShakePlugin(
      onPhoneShaken: () {
        setState(() {
      count=count+10;
    });
  },
      },
    )..startListening();
  }

  void dispose() {
    super.dispose();
    _shakePlugin.stopListening();
  }

  Future<String> getjsondata() async {
    try {
      var response = await http.get(
          'https://api.unsplash.com/search/photos?per_page=${count}&client_id=TcAQEO3JoMG90U7Rl-YUiDo1x9XbZukzMOMQhxUVCV4&query=${_search}');
      setState(() {
        var converted = json.decode(response.body);
        data = converted['results'];
      });
    } catch (e) {}
    return 'success';
  }
  void saveImage(int i) async {
    var url = data[i]['urls']['small'].toString();

    var imageId = await ImageDownloader.downloadImage(url);
    path = await ImageDownloader.findPath(imageId);
  }

  @override
  Widget build(BuildContext context) {
    getjsondata();
    return GestureDetector(
      child: SwipeDetector(
        child: Container(
          child: Image.network(
            data[index]['urls']['small'],

I want to increase the count of images i recieve from api on shake of screen but this is not working even if i have installed all the libraries and all.


Solution

  • Calling your getjsondata method in the build method will cause the ui to render infinitely because you're calling setState in getjsondata. I think the shake plugin is working fine but its result is void because the screen is in an infinite render state.

    If you move getjsondata to a FutureBuilder, remove the setState call from inside the getjsondata method and render your ui on the result of the Future your code should work.