Home > Blockchain >  How to scroll when button is clicked in flutter?
How to scroll when button is clicked in flutter?

Time:03-14

I want when I click on the Button it shows the next 3 containers that in the listVeiw it is horizontally direction. Here is my code. when I tap for the first time it works, but it doesn't work for the others taps

    import 'package:flutter/material.dart';

class FindCars extends StatefulWidget {
  const FindCars({Key? key}) : super(key: key);

  @override
  State<NewWayToFindCars> createState() => _NewWayToFindCarsState();
}

class _NewWayToFindCarsState extends State<NewWayToFindCars> {
  var pricesListNumber = 10;
  int counter = 1;

  List months = [
    'يناير',
    'فبراير',
    'مارس',
    'ابريل',
    'مايو',
    'يونيو',
    'يوليو',
    'اغسطس',
    'سبتمبر',
    'اكتوبر',
    'نوفمبر',
    'ديسمبر'
  ];

  var currentMonth = new DateTime.now().month;
  var currentDay = new DateTime.now().day;

  late ScrollController _scrollController;

  @override
  void initState() {
    _scrollController = ScrollController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print(months[currentMonth - 1]);
    print(currentDay);
    print(DateTime.now());
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: Directionality(
        textDirection: TextDirection.rtl,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Text(
              '${months[currentMonth - 1]}  2022',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.black,
                fontFamily: 'cairo',
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InkWell(
                  onTap: () {
                    
                    _scrollController.animateTo(-200,
                        duration: const Duration(milliseconds: 500),
                        curve: Curves.easeInOut);
                  },
                  child: Container(
                    child: Icon(Icons.remove, size: 22),
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      color: Color(0xFFDCEDC8).withOpacity(0.5),
                      border: Border.all(
                        color: Color(0xFFDDE7DD).withOpacity(0.5),
                        width: 2.5,
                      ),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10),
                        bottomLeft: Radius.circular(10),
                      ),
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    _scrollController.animateTo(200,
                        duration: const Duration(milliseconds: 500),
                        curve: Curves.easeInOut);
                  },
                  child: Container(
                    child: Center(child: Icon(Icons.add_sharp, size: 22)),
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      color: Color(0xFFDCEDC8).withOpacity(0.25),
                      border: Border.all(
                        color: Color(0xFFDDE7DD).withOpacity(0.5),
                        width: 2.5,
                      ),
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(10),
                        bottomRight: Radius.circular(10),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height * 0.1,
              child: ListView(
                controller: _scrollController, // scroll contoller
                scrollDirection: Axis.horizontal,
                children: new List.generate(
                  pricesListNumber,
                  (index) => Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Container(
                      child: Center(child: Text('${currentDay  }')),
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.5),
                            spreadRadius: 5,
                            blurRadius: 7,
                            offset: Offset(0, 3), // changes position of shadow
                          ),
                        ],
                        color: Color(0xFFDCEDC8).withOpacity(0.5),
                        border: Border.all(
                          color: Color(0xFFDDE7DD).withOpacity(0.5),
                          width: 2.5,
                        ),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      height: 50,
                      width: MediaQuery.of(context).size.width * 0.25,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Here is my code for the UI, and now it is only works in the first click put it does not work until the end. Can you please help me with that?

CodePudding user response:

Just use a scrollController, attach it to your ListView builder, then on your Button's onPress/onTap method, call _scrolController.animateTo(someOffset)

Copy the code below and run into your project. I have customized it based on your needs.

import 'package:flutter/material.dart';

class TestView extends StatefulWidget {
  const TestView({Key? key}) : super(key: key);

  @override
  State<TestView> createState() => _TestViewState();
}

class _TestViewState extends State<TestView> {
  late ScrollController _scrollController;

  @override
  void initState() {
    _scrollController = ScrollController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ElevatedButton(
                  onPressed: () {
                    _scrollController.animateTo(-500,
                        duration: const Duration(milliseconds: 500),
                        curve: Curves.easeInOut);
                  },
                  child: const Text("-")),
              ElevatedButton(
                onPressed: () {
                  _scrollController.animateTo(500,
                      duration: const Duration(milliseconds: 500),
                      curve: Curves.easeInOut);
                },
                child: const Text(" "),
              ),
            ],
          ),
          SizedBox(
            height: 200,
            child: ListView(
              controller: _scrollController,
              scrollDirection: Axis.horizontal,
              children: List.generate(20, (index) {
                return Container(
                  color: Colors.amber,
                  height: 100,
                  width: 100,
                  margin: const EdgeInsets.only(right: 10),
                  child: Center(child: Text("$index")),
                );
              }),
            ),
          )
        ],
      ),
    );
  }
}

CodePudding user response:

Attach a ScrollController to your scrollable widget and then use scrollController.animateTo(//offset) to reach where you want. Do check the animateTo method on this page.

EDIT: sample code:

  ScrollController scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                scrollController.animateTo(0,
                    duration: Duration(seconds: 1), curve: Curves.easeIn);
              },
              child: Text("go top")),
          Expanded(
            flex: 1,
            child: ListView.builder(
              controller: scrollController,
              itemCount: 100,
              itemBuilder: (context, index) {
                return Text('This is it.');
              },
            ),
          ),
        ],
      ),
    );
  }

Try it in your IDE.

EDIT:

Here is the problem in your code, you need to decrease/increase the current offset of the scroll controller by subtracting/adding 200 from the scrollController.position. You are getting it moved for the first time because at that time offset is not at 200 and for the second time it is there at 200. That is why it is not moving which is obviously no error.

  • Related