dart 如何滚动时+按钮被点击 Flutter ?

4xy9mtcn  于 2023-09-28  发布在  Flutter
关注(0)|答案(3)|浏览(84)

我想当我点击+按钮时,它会显示下3个容器,在listVeiw中是水平方向。这是我的代码。当我第一次点击它的工作,但它不工作的其他水龙头

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,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

这里是我的代码的UI,现在它只在第一次点击把它不工作,直到最后。你能帮我吗?

gcuhipw9

gcuhipw91#

将ScrollController附加到可滚动小部件,然后使用scrollController.animateTo(//offset)到达您想要的位置。检查this页面上的animateTo方法。
编辑:示例代码:

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.');
              },
            ),
          ),
        ],
      ),
    );
  }

在你的IDE中试试。
编辑:
这里是你的代码中的问题,你需要通过从scrollController. position减去/增加200来减少/增加滚动控制器的当前偏移量。第一次移动它是因为此时偏移量不是200,第二次移动时偏移量是200。这就是为什么它没有移动,这显然是没有错误的。

cyvaqqii

cyvaqqii2#

只需使用scrollController,将其附加到ListView构建器,然后在Button的onPress/onTap方法上调用_scrolController.animateTo(someOffset)
复制下面的代码并运行到您的项目中。我根据你的需要定制的。

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")),
                );
              }),
            ),
          )
        ],
      ),
    );
  }
}
goqiplq2

goqiplq23#

也许你会对另一个解决方案感兴趣,这是个很粗糙的例子,但我想大家都能理解.

class TestScrollOnClick extends StatelessWidget {
  TestScrollOnClick({super.key});

  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: InkWell(
        child: Icon(Icons.arrow_left),
        onTap: (){
          _scrollController.animateTo(
            _scrollController.offset + 50,
            duration: Duration(milliseconds: 100),
            curve: Curves.bounceIn,
          );
        },
      ),

      subtitle: SingleChildScrollView(
        controller: _scrollController,
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            Container(
              width: 100,
              height: 50,
              color: Colors.redAccent,
            ),

            Container(
              width: 100,
              height: 50,
              color: Colors.redAccent,
            ),
            Container(
              width: 100,
              height: 50,
              color: Colors.redAccent,
            ),
            Container(
              width: 100,
              height: 50,
              color: Colors.redAccent,
            ),
            Container(
              width: 100,
              height: 50,
              color: Colors.redAccent,
            ),

          ],
        ),
      ),

      trailing: InkWell(
        child: Icon(Icons.arrow_left),
        onTap: (){
          _scrollController.animateTo(
            _scrollController.offset - 50,
            duration: Duration(milliseconds: 100),
            curve: Curves.bounceIn,
          );
        },
      ),
    );
  }
}

相关问题