user3217522
user3217522

Reputation: 6294

Implementing a bidirectional listview in Flutter

How do you implement a bidirectional scroll view in Flutter? ListView has a scrollDirection field however it can only take either Axis.horizontal or Axis.vertical. Is is possible to have both?

Upvotes: 7

Views: 8095

Answers (2)

Collin Jackson
Collin Jackson

Reputation: 116838

Here's a potential solution using an outer SingleChildScrollView. You could also use a PageView of multiple ListViews if you're ok with the offscreen ListViews being torn down.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    return new Scaffold(
      body: new SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: new SizedBox(
          width: 1000.0,
          child: new ListView.builder(
            itemBuilder: (BuildContext context, int i) {
              return new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: new List.generate(5, (int j) {
                  return new Text("$i,$j", style: themeData.textTheme.display2);
                }),
              );
            },
          ),
        ),
      ),
    );
  }
}

Upvotes: 7

Collin Jackson
Collin Jackson

Reputation: 116838

See my answer on this question that I posted and self-answered. I'm not aware of a way to do it with a single Scrollable, although I can imagine it being useful.

You can't easily solve this with an infinite-length ListView.builder because it only goes in one direction. If you want to wrap in both directions, it is possible to simulate bidirectional wrapping with a Stack of two Viewports going in opposite directions.

There's a code sample on the question too (you might have to modify the answer a bit if you don't want wrapping).

Upvotes: 1

Related Questions