Widget Slider and flutter_staggered_grid_view Slider

Asked

Viewed 290 times

0

How to individualize the actions of these Widget Slides?

The problem is that when I slip one, the other also reacts as if it were a clone.

inserir a descrição da imagem aqui

I’m using the "flutter_staggered_grid_view Slider 3.0 library example".

home.Dart.

import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:http/http.dart' as http;
import 'package:my_blynk_2_socke_reiniciu_2_ghit_hub/bloc/slider_bloc.dart';
import 'package:my_blynk_2_socke_reiniciu_2_ghit_hub/model.dart';
import 'package:my_blynk_2_socke_reiniciu_2_ghit_hub/slider_V0.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  WebSocketChannel channel;
  SliderBloc bloc = new SliderBloc();
  final List<String> listA = [];

  FutureBuilder<List<HitsArrayImage>> futureBuilder;

  int _counter = 0;

// Dados variavel recebe jsonString no get dado
  var values;
//--------------------------------------------------------

  String pegaVlSlidServidEnviSlid;
  var sendGargSliderBloc;
  var snapshotDados;

//--------------------------------------------------------
  ///  Variaveis Texto do Container
  String recTextContaine;

  ///
//--------------------------------------------------------
  var timer;
  Timer imer;
  bool isStopped = false;
//--------------------------------------------------------
  double writDoubleValue;
//--------------------------------------------------------
  ///
  Future<List<HitsArrayImage>> _getDado() async {
    final response =
        await http.get('http://192.168.xxx.xxx:0000/chm_pin_d/posts');
    if (response.statusCode == 200) {
      values = hitsArrayFromJsonImage(response.body);
      return values;
    } else {
      return null;
      //throw Exception('Falha ao carregar um post');
    }
  }

  ///
////////////////////////////////////////////////////////////////////////////////////////
  ///
  sec5Timer() {
    Timer.periodic(Duration(seconds: 5), (timer) {
      if (isStopped) {
        timer.cancel();
      }
      print("Dekhi 5 sec ");
    });
  }

  ///
////////////////////////////////////////////////////////////////////////////////////////
  addDoubleToSF(id, writDoubleValue) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setDouble(
      'writDoubleValue',
      writDoubleValue,
    );
    prefs.setString(
      'id',
      id,
    );
  }

////////////////////////////////////////////////////////////////////////////////////////
  ///
  @override
  void dispose() {
    channel.sink.close();
    super.dispose();
  }

  ///
  @override
  void initState() {
    channel = IOWebSocketChannel.connect(
        'ws://192.168.xxxxxx:0000/auth_token/slider/value');
    super.initState();
  }

  ///
  @override
  Widget build(BuildContext context) {
    print("Recosntruindo Builder...... ");
    return Scaffold(
        drawer: Drawer(),
        body: Stack(
          children: <Widget>[
            CustomScrollView(
              slivers: <Widget>[
                //custom scroll behaviour for appbar
                SliverAppBar(
                  iconTheme: new IconThemeData(color: Colors.blue),
                  floating: true,
                  snap: true,
                  //seethrough
                  backgroundColor: Colors.transparent,
                  //shadow
                  elevation: 0.0,
                  flexibleSpace: FlexibleSpaceBar(
                    title: StreamBuilder(
                        stream: bloc.output,
                        builder: (context, snapshot) {
                          snapshotDados = snapshot.hasData ? snapshot.data : 1;
                          print(snapshotDados);
                          return Text(
                            snapshot.hasData ? '${snapshot.data}' : 'valor',
                            //"Automação",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 26.0,
                                fontWeight: FontWeight.bold),
                          );
                        }),
                  ),
                  centerTitle: true,
                ),

                ///
///////////////////////////////////////////////////////////////////////////////////
                ///    FutureBuilder
                FutureBuilder<List<HitsArrayImage>>(
                    future: _getDado(),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData || snapshot.hasError) {
                        return SliverToBoxAdapter(
                          child: Container(
                            height: 200.0,
                            alignment: Alignment.center,
                            child: CircularProgressIndicator(
                              valueColor:
                                  AlwaysStoppedAnimation<Color>(Colors.orange),
                            ),
                          ),
                        );
                      } else {
                        return SliverStaggeredGrid.count(
                          crossAxisCount: 8,
                          crossAxisSpacing: 0, //1.0,
                          mainAxisSpacing: 0, //1.0,
                          staggeredTiles: snapshot.data.map((doc) {
                            return StaggeredTile.count(doc.x, doc.y);
                          }).toList(),

                          ///
////////////////////////////////////////////////////////////////////////////////////////////////
                          ///
                          children: snapshot.data.map((doc) {
                            return Container(
                              child: Card(
                                color: Color.fromRGBO(255, 255, 255, 255),
                                child: InkWell(
                                    onTap: () {},
                                    child: Stack(
                                      children: <Widget>[
                                        ///
///////////////////////////////////////////////////////////////////////////////////////////////////////
                                        ///   Title
                                        Visibility(
                                          visible: doc
                                              .flagTextTitle, // == true ? true : false,
                                          child: Positioned(
                                            child: Container(
                                              child: Column(
                                                children: <Widget>[
                                                  Padding(
                                                    padding: new EdgeInsets.all(
                                                        doc.padding),
                                                    child: Center(
                                                      child:
                                                          Text(doc.titleFora),
                                                    ),
                                                  ),
                                                  SizedBox(
                                                    height: 5.0,
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ),

//////////////////////////////////////////////////////////////////////////////////////////////////
                                        ///  SLIDER... 1
                                        Visibility(
                                          child: StreamBuilder(
                                              stream: bloc.output,
                                              //initialData: doc.setChangedSlider,
                                              builder: (context, snapshot) {
                                                print(snapshot.data);
                                                return widgetSliderV0(
                                                    doc.sId,
                                                    doc.flagSet,
                                                    doc.setChangedSlider0,
                                                    snapshotDados,
                                                    bloc.newRatingRetorno,
                                                    snapshot.data,
                                                    onClickActionV0:
                                                        (newRatingRetorno) {
                                                  {
                                                    addDoubleToSF(doc.sId,
                                                        newRatingRetorno);
                                                    channel.sink.add(
                                                        '$newRatingRetorno');
                                                    bloc.setSliderBloc0(
                                                        newRatingRetorno);
                                                  }
                                                });
                                              }),
                                        ),

                                        ///
///////////////////////////////////////////////////////////////////////////////////////////////////
                                        ///
                                      ],
                                    )),
                              ),
                            );
                          }).toList(),
                        );
                      }
                    })
              ],
            ),
          ],
        ));
  }
}

slider_V0.Dart.

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

var textButtOnD;
var textButtOfD;
var titleForaD;
var posD;
var xD;
var yD;
var aD;
var rD;
var gD;
var bD;
String namePinD;
String nameModD;
var setChangedSliderD;
var flagSetD;
String flagSetNameD;
var flagSetCores;
var buttSizWidtD;
var buttSizHeigD;
var colorButD;
var colorContD;
var flagTextTitleD;
var flagButtD;
var flagSlidD;
var flagSlidBD;
var flagLedD;
//
// **********************************************************************************

bool flagSliderAqui = false;
var _valueA = 0.0;
var _valueB;
bool flagSlidVl = false;
var setsnapshotdata;

var setValorSlider; // = 1.0;

double writDoubleValue;
double readDoubleValue;
var readDoubleid;



Container widgetSliderV0(
  sIdJsonString,
  flagSet,
  setChangedSlider,
  snapshotDados,
  newRatingRetorno, 
  snapshotdata,

  {
  Function onClickActionV0,
}) {
 
        

  return Container(
    color: Colors.orange[50],
    child: Row(

        children: [
          Icon(
            Icons.ac_unit,
            size: 30,
          ),
          Expanded(
             child: Slider(
             
              value: setValorSlider, 
              min: 1,
              max: 250,
              activeColor: Colors.red,
              inactiveColor: Colors.blue,
              label: 'Set a value', 
              onChanged: (double newValue) {
                _valueA = newValue; 
                onClickActionV0(_valueA);
              },

              onChangeEnd: (double newValue) {
              _makePutRequest(sIdJsonString, newValue);
              }

            ),
       ),
    ]),
  );

}

// ======================   PUT    ==========================================================
//
const Map<String, String> headers = {"Content-type": "application/json"};
  _makePutRequest(sIdJsonString, setChangedSliderD) async {

  String jsonputi = jsonEncode({
    "setChangedSlider": setChangedSliderD,
  });

  String url = '${'http://192.168.xxx.xxx:0000/chm_pin_d/update/setslider/'}' +
      sIdJsonString;
 
  Response response = await put(url, headers: headers, body: jsonputi);
  int statusCode = response.statusCode;
  String body = response.body;
  print('Status: $statusCode, $body');
}

json

{
"valueSliderArray": [],
"color": [
250,
250,
250,
250
],
"colorBut": [
255,
38,
42,
45
],
"colorCont": [
255,
38,
42,
45
],
"textColor": [
"254",
"254",
"254",
"254"
],
"splashColor": [
"240",
"240",
"240",
"240"
],
"_id": "5e794ffe40d78f0764b808c5",
"image": "",
"pos": 0,
"titleFora": "Nam",
"fontSize": 9.4,
"textButtOn": "ON",
"textButtOf": "OFF",
"x": 4,
"y": 1,
"a": 255,
"r": 38,
"g": 42,
"b": 45,
"namePin": "V0",
"nameMod": "Mod",
"flagSetName": "ON",
"flagSet": "0",
"setChangedSlider0": 53.873965170047704,
"flagSetCores": 0,
"flag_text_title": false,
"flagButtTooglePush": false,
"flag_butt": false,
"flag_slid": false,
"flag_slid_b": true,
"flag_led": false,
"typea": "Container",
"alignment": "center",
"typeb": "RaisedButton",
"padding": 1.1,
"elevation": 8.2,
"click_event": "route://productDetail?goods_id=120",
"typec": "Text",
"data": "But D1",
"__v": 0,
"valueA": 55.455
},
{
"valueSliderArray": [],
"color": [
250,
250,
250,
250
],
"colorBut": [
255,
38,
42,
45
],
"colorCont": [
255,
38,
42,
45
],
"textColor": [
"254",
"254",
"254",
"254"
],
"splashColor": [
"240",
"240",
"240",
"240"
],
"_id": "5e79500240d78f0764b808c6",
"image": "",
"pos": 0,
"titleFora": "Nam",
"fontSize": 9.4,
"textButtOn": "ON",
"textButtOf": "OFF",
"x": 4,
"y": 1,
"a": 255,
"r": 38,
"g": 42,
"b": 45,
"namePin": "V1",
"nameMod": "Mod",
"flagSetName": "ON",
"flagSet": "0",
"flagSetCores": 0,
"flag_text_title": false,
"flagButtTooglePush": false,
"flag_butt": false,
"flag_slid": false,
"flag_slid_b": true,
"flag_led": false,
"typea": "Container",
"alignment": "center",
"typeb": "RaisedButton",
"padding": 1.1,
"elevation": 8.2,
"click_event": "route://productDetail?goods_id=120",
"typec": "Text",
"data": "But D1",
"__v": 0,
"valueB": 12.55,
"setChangedSlider0": 152.12037123359093
},
{
"valueSliderArray": [],
"color": [
250,
250,
250,
250
],
"colorBut": [
255,
38,
42,
45
],
"colorCont": [
255,
38,
42,
45
],
"textColor": [
"254",
"254",
"254",
"254"
],
"splashColor": [
"240",
"240",
"240",
"240"
],
"_id": "5e7d24af7486c046f0b53191",
"image": "",
"pos": 0,
"titleFora": "Nam",
"fontSize": 9.4,
"textButtOn": "ON",
"textButtOf": "OFF",
"x": 4,
"y": 1,
"a": 255,
"r": 38,
"g": 42,
"b": 45,
"namePin": "V1",
"nameMod": "Mod",
"flagSetName": "ON",
"flagSet": "0",
"flagSetCores": 0,
"flag_text_title": false,
"flagButtTooglePush": false,
"flag_butt": false,
"flag_slid": false,
"flag_slid_b": true,
"flag_led": false,
"typea": "Container",
"alignment": "center",
"typeb": "RaisedButton",
"padding": 1.1,
"elevation": 8.2,
"click_event": "route://productDetail?goods_id=120",
"typec": "Text",
"data": "But D1",
"__v": 0,
"valueB": 12.55,
"setChangedSlider0": 152.12037123359093
}
]

I am creating an app for residential taking that will contain many Slides. I put a little code down, but I’ve tried it a couple of ways, but I can’t seem to fix it, so I appreciate all your help.

1 answer

0


Your code is a bit messy and complicated to understand, so I’ll give you an example of how to do and you apply for your case...

1º Create a Widget to be yours CustomSlider

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

  double sliderValue = 0;

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

class _MySliderState extends State<MySlider> {
  @override
  Widget build(BuildContext context) {
    return Slider(
      value: widget.sliderValue,
      onChanged: (double value){
        setState((){
          widget.sliderValue = value;
        });
      },
    );
  }
}

Note: Instead of exposing the property sliderValue you can pass parameters to your widget, as I saw you already do in your source, so you pass to it yours Sink of the Bloc and instead of feeding the sliderValue you pass the direct value to the Sink.

2nd Create a class to store your Sliders and so you have a better control of them

class SliderController{
  SliderController({@required this.index, @required this.slider});
  int index;
  MySlider slider;
}

3º Implement your CustomSlider

class MyWidget extends StatelessWidget {
  MyWidget(){
    sliders.add(SliderController(index: 0, slider: MySlider()));
    sliders.add(SliderController(index: 1, slider: MySlider()));
    sliders.add(SliderController(index: 2, slider: MySlider()));
  }

  final List<SliderController> sliders = List<SliderController>();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: ListView(
            children: sliders.map((slider){
              return slider.slider;
            }).toList(),
          )
        ),
        RaisedButton(
          child: Text("Pegar valor do 2º slider"),
          onPressed: (){
            print(sliders[1].slider.sliderValue);
          }
        )
      ],
    );
  }
}

Explanation

Doing so, you will let each CustomSlider created by you if "self-control" so one will not affect the other. Another thing is that with a list of these Widgets you can do several controls you want, as you will have everything stored in one place.

Below I leave the complete code that can be tested on Dartpad (Just copy the code and paste there)

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  MyWidget(){
    sliders.add(SliderController(index: 0, slider: MySlider()));
    sliders.add(SliderController(index: 1, slider: MySlider()));
    sliders.add(SliderController(index: 2, slider: MySlider()));
  }

  final List<SliderController> sliders = List<SliderController>();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: ListView(
            children: sliders.map((slider){
              return slider.slider;
            }).toList(),
          )
        ),
        RaisedButton(
          child: Text("Pegar valor do 2º slider"),
          onPressed: (){
            print(sliders[1].slider.sliderValue);
          }
        )
      ],
    );
  }
}

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

  double sliderValue = 0;

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

class _MySliderState extends State<MySlider> {
  @override
  Widget build(BuildContext context) {
    return Slider(
      value: widget.sliderValue,
      onChanged: (double value){
        setState((){
          widget.sliderValue = value;
        });
      },
    );
  }
}

class SliderController{
  SliderController({@required this.index, @required this.slider});
  int index;
  MySlider slider;
}
  • Hi Matheus, I made some changes to the code you posted to adapt it to mine and now the Sliders are individualized. I don’t know if the code is correct for what I research it seems not a good practice to pass parameters in the "Constructor", but it was the only way I could. I updated the Git Link in the above answer and updated the code with the changes and gave an organized, vlw help I was a long time stuck in this question and now I will give sequence in my pleasant project automation of a hobbist rs.

  • @mauroviana For nothing, I’m glad it was useful to you! And in no way, pass parameters in the builder NO It’s a bad practice, rest assured... Any questions we’re here to help you, and you have my contacts on my profile too.

  • @mauroviana if my answer solved this your case, please mark it as accepted using the profile you used to ask the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.