Как сделать так, чтобы средний виджет прокручиваемой строки отображался слева при запуске страницы? - PullRequest
1 голос
/ 06 августа 2020

У меня сложная проблема - по крайней мере для меня - здесь.

Итак, у меня есть список Container, помещенный внутри Row. И затем Row обернут с использованием SingleChildScrollView и имеют scrollDirection: Axis.horizontal,, поэтому Row можно было прокручивать по горизонтали.

Вот код:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Scrollable WIdgets"),
      ),
      body: Center(
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            children: <Widget>[
              // Container #1 ============================
              Container(
                margin: EdgeInsets.all(15.0),
                color: Colors.red,
                height: 250.0,
                width: 250.0,
                child: Center(
                  child: Text('A'),
                ),
              ),
              
              // Container #2 ============================
              Container(
                margin: EdgeInsets.all(15.0),
                color: Colors.blue,
                height: 250.0,
                width: 250.0,
                child: Center(
                  child: Text('B'),
                ),
              ),
              
              // Container #3 ============================
              Container(
                margin: EdgeInsets.all(15.0),
                color: Colors.green,
                height: 250.0,
                width: 250.0,
                child: Center(
                  child: Text('C'),
                ),
              ),
              
              // Container #4 ============================
              Container(
                margin: EdgeInsets.all(15.0),
                color: Colors.yellow,
                height: 250.0,
                width: 250.0,
                child: Center(
                  child: Text('D'),
                ),
              ),
              
              // Container #5 ============================
              Container(
                margin: EdgeInsets.all(15.0),
                color: Colors.pink,
                height: 250.0,
                width: 250.0,
                child: Center(
                  child: Text('E'),
                ),
              ),
              
              
            ]
            ),
          ),
      ),
    );
  }
}

Когда экран построен, Контейнер A (или Контейнер №1) будет показан в самом левом углу экрана: Initial

My question is, how to make the Container C (or container #3) show up in the most left of the screen on the screen's first build? but the horizontal scroll function still running as usual. (see the image below for more understanding)

Цель

1 Ответ

2 голосов
/ 06 августа 2020

Так как вы знаете ширину своих дочерних элементов, вы можете просто явно установить свойство controller для SingleChildScrollView с помощью ScrollController и определить initialScrollOffset. Я думаю, что ScrollController нужно было бы создать в виджете с отслеживанием состояния и использовать в качестве переменной, поэтому примерно так:

class _MyHomePageState extends State<MyHomePage> {
  ScrollController controller = ScrollController(initialScrollOffset: 560.0);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Scrollable WIdgets"),
      ),
      body: Center(
        child: SingleChildScrollView(
          controller: controller,
          (...)

Значение initialScrollOffset определяется шириной дочерних строк плюс их поля, поэтому 2*250 + 4*15 = 560

...