flutterflutter-layoutswipegesturedetectormaterialbutton

Flutter- per my code how to make material button invisible on swiping left and re-appear on swiping right


I am creating an APP which has a lot of emphasis on the image in the background as such, their is text in arabic on that image per line and I want to add "material buttons" on top of this text. I was able to do this ...but then I want the button to be invisible once I swipe left, and re-appear when I swipe to the right, I did use gesture Detector and it does print on the screen if I swipe right or swipe left ..I was trying to input the gesture detector within the material button but everytime I try this it sends an error that's why I have the gesture detector on the bottom of the whole code please help ...

please help

import 'dart:io';
import 'package:Quran_highlighter/main.dart';
import 'package:flutter/rendering.dart';
import 'package:system_shortcuts/system_shortcuts.dart';
import 'package:Quran_highlighter/Widgets/NavDrawer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zoom_widget/zoom_widget.dart';
import 'package:flutter/gestures.dart';

class Aliflaammeem extends StatefulWidget {
  @override
  _AliflaammeemState createState() => _AliflaammeemState();
}

class _AliflaammeemState extends State<Aliflaammeem> {
  var nameList = new List<String>();
    final items = List<String>.generate(20, (i) => "Item ${i + 1}");

  List<MaterialButton> buttonsList = new List<MaterialButton>();

  @override
  void initState(){
    super.initState();
    nameList.add("I love");
    nameList.add("my ALLAH");
    nameList.add("SWT Very Much");

List<Widget> buildButtonswithName(){
  int length = nameList.length;
  for (int i=0; i<length; i++){
    buttonsList.add(new MaterialButton(
      height:40.0,
      minWidth: 300.0,
      color: Colors.blue,
      textColor: Colors.white,

  ));
  }
}  }

List<String> labels = ['apple', 'banana', 'pineapple', 'kiwi'];
// List<VoidCallback> actions = [_buyApple, _doSomething, _downloadData, () => print('Hi')
// ];
   bool _visible = true;
  int _counter = 0;
  double _initial = 0.0;

  var textHolder = "";

  changeTextEnglish() {
    setState(() {
      bool _visible = true;
         _visible =  _visible;
      textHolder = "All Praise and Thanks is to Allah the lord of the worlds";
    });
  }

  changeTextArabic() {
    bool _visible = true;
    setState(() {
      _visible =  _visible;
    });
  }

  @override
  Widget build(BuildContext context) {
    final title = 'Dismissing Items';
    // appBar: AppBar(
    //   title: Text('Para 1, Pg2'),
    //   backgroundColor: Colors.teal[400],

    // SystemChrome.setPreferredOrientations(
    //     [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    return Scaffold(
        body: Center(
            child: Stack(fit: StackFit.expand, children: <Widget>[
      Stack(
        children: <Widget>[
          SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: SafeArea(
              top: true,
              bottom: true,
              right: true,
              left: true,
              child: Image(
                  image: AssetImage('test/assets/quranpg0.png'),
                  fit: BoxFit.cover
              ),   
            ),
          ),
        ],
          ),
        
  

      Stack(
        children: <Widget>[
        // for(int i = 0; i< labels.length; i++)
        // weather_app/lib/page/settings_page.dart -- line ~81
    // ListView.builder(
    //       itemCount: items.length,
    //       itemBuilder: (context, index) {
    //         final item = items[index];

    //         return Dismissible(
    //           // Each Dismissible must contain a Key. Keys allow Flutter to
    //           // uniquely identify widgets.
    //           key: Key(item),
    //           // Provide a function that tells the app
    //           // what to do after an item has been swiped away.
    //           onDismissed: (direction) {
    //             // Remove the item from the data source.
    //             setState(() {
    //               items.removeAt(index);
    //             });
    //         // Then show a snackbar.
    //             Scaffold.of(context)
    //                 .showSnackBar(SnackBar(content: Text("$item dismissed")));
    //           },
    //           // Show a red background as the item is swiped away.
    //           background: Container(color: Colors.green),
    //           secondaryBackground: Container(color: Colors.red),
    //           child: ListTile(title: Text('$item'))
        
         
    //         );
    //           },
    //         ),

        Container(
          child: Align(
            alignment: Alignment(.27, 0.1
            ),
          //   child: Visibility(
          // visible: _visible,
          // maintainSize: true,
          // maintainAnimation: true,
          // maintainState: true,
              child: MaterialButton(
              height: 70.0,
              // minWidth: 36.5,
              minWidth: 85.0,
              onPressed: () => changeTextArabic(),
              onLongPress: () => changeTextEnglish(),
              // child: Text(labels[i]),
              child: Text('$textHolder'),
              color: Colors.cyan[400],
              // color: Colors.purple[300],
              highlightColor: Colors.blue,
              textColor: Colors.white,
              padding: EdgeInsets.only(left: 10, top: 2, right: -1, bottom: 5
              ),
              ),
            ),
            ),
            for(int i = 0; i< labels.length; i++)
               Container(
          child: Align(
            alignment: Alignment(-.5, 0.1
            ),
//  child: Text("The Most Loving",
//  style: TextStyle(
//    fontSize: 15.0,
//    backgroundColor: Colors.cyan,
//    height: 1.0,
//    fontWeight: FontWeight.bold
//    ),
            child: MaterialButton(
              height: 70.0,
              minWidth: 36.5,
              onPressed: () => changeTextArabic(),
              onLongPress: () => changeTextEnglish(),
              // Positioned(
              // top: 21,
              child: Text(labels[i]),
              disabledTextColor: Colors.transparent,
              color: Colors.cyan[300],
              // color: Colors.purple[300],
              highlightColor: Colors.blue,
              textColor: Colors.white,
              padding: EdgeInsets.only(left: 46, top: 2, right: -20, bottom: 5),
            ),
//  ),
          ),
        )
      ],
      ),
        GestureDetector(onPanUpdate: (DragUpdateDetails details) {
        if (details.delta.dx > 0) {
          print("right swipe english");
          changeTextEnglish();
          setState(() {
 
          });
        } else if (details.delta.dx < 0) {
          print("left swipe arabic");
          changeTextArabic();
          setState(() {
          });
        }
      })
    ])));
  }
}

Solution

  • I think I got want you want.

    First I added a condition to display the MaterialButton like so:

    (_visible) ? MaterialButton(...) : Container()
    

    Then inside "changeTextEnglish" and "changeTextArabic":

    1. I changed _visible to absolute value
    2. I deleted your lines "bool _visible = ..." because here you where creating local variable inside the function and therefore could no longer access _visible as the attribute of _AliflaammeemState.

    So "changeTextEnglish" and "changeTextArabic" became:

    changeTextEnglish() {
        setState(() {
          _visible = true;
          textHolder = "All Praise and Thanks is to Allah the lord of the worlds";
        });
      }
    
    changeTextArabic() {
        setState(() {
          _visible = false;
        });
      } 
    

    Which fives me the following working code (I deleted your comment to be able to see the issue so maybe don't copy paste the entire code.

    class Aliflaammeem extends StatefulWidget {
      @override
      _AliflaammeemState createState() => _AliflaammeemState();
    }
    
    class _AliflaammeemState extends State<Aliflaammeem> {
      var nameList = new List<String>();
      final items = List<String>.generate(20, (i) => "Item ${i + 1}");
    
      List<MaterialButton> buttonsList = new List<MaterialButton>();
    
      @override
      void initState() {
        super.initState();
        nameList.add("I love");
        nameList.add("my ALLAH");
        nameList.add("SWT Very Much");
      }
    
      List<String> labels = ['apple', 'banana', 'pineapple', 'kiwi'];
      bool _visible = true;
      int _counter = 0;
      double _initial = 0.0;
    
      var textHolder = "";
    
      changeTextEnglish() {
        setState(() {
          _visible = true;
          textHolder = "All Praise and Thanks is to Allah the lord of the worlds";
        });
      }
    
      changeTextArabic() {
        setState(() {
          _visible = false;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        final title = 'Dismissing Items';
        return Scaffold(
            body: Center(
                child: Stack(fit: StackFit.expand, children: <Widget>[
          Stack(
            children: <Widget>[
              SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: SafeArea(
                  top: true,
                  bottom: true,
                  right: true,
                  left: true,
                  child: Image(image: AssetImage('test/assets/quranpg0.png'), fit: BoxFit.cover),
                ),
              ),
            ],
          ),
          Stack(
            children: <Widget>[
              Container(
                child: Align(
                  alignment: Alignment(.27, 0.1),
                  child: _visible
                      ? MaterialButton(
                          height: 70.0,
                          minWidth: 85.0,
                          onPressed: () => changeTextArabic(),
                          onLongPress: () => changeTextEnglish(),
                          child: Text('$textHolder'),
                          color: Colors.cyan[400],
                          highlightColor: Colors.blue,
                          textColor: Colors.white,
                          padding: EdgeInsets.only(left: 10, top: 2, right: -1, bottom: 5),
                        )
                      : Container(),
                ),
              ),
              for (int i = 0; i < labels.length; i++)
                Container(
                  child: Align(
                    alignment: Alignment(-.5, 0.1),
                    child: MaterialButton(
                      height: 70.0,
                      minWidth: 36.5,
                      onPressed: () => changeTextArabic(),
                      onLongPress: () => changeTextEnglish(),
                      child: Text(labels[i]),
                      disabledTextColor: Colors.transparent,
                      color: Colors.cyan[300],
                      highlightColor: Colors.blue,
                      textColor: Colors.white,
                      padding: EdgeInsets.only(left: 46, top: 2, right: -20, bottom: 5),
                    ),
    //  ),
                  ),
                )
            ],
          ),
          GestureDetector(onPanUpdate: (DragUpdateDetails details) {
            if (details.delta.dx > 0) {
              print("right swipe english");
              changeTextEnglish();
              setState(() {});
            } else if (details.delta.dx < 0) {
              print("left swipe arabic");
              changeTextArabic();
              setState(() {});
            }
          })
        ])));
      }
    }