Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force PhotoViewGallery class to start showing specific image instead of the first one

Tags:

flutter

dart

I'm in trouble again and I hope someone can help me again.
I would like to have PhotoViewGallery Class display the page with a specific id first
instead of the first page of the Pages list.
In the following code

import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

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

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

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

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;

  final List<String> listaPagine = [
    'https://picsum.photos/id/451/200/300',
    'https://picsum.photos/id/200/200/300'
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('# $_currentIndex'),
      ),
      body: PhotoViewGallery.builder(
        itemCount: listaPagine.length,
        builder: (BuildContext context, int index) {
          String myImg = listaPagine[index];

          return PhotoViewGalleryPageOptions(
            imageProvider: NetworkImage(myImg),
          );
        },
        onPageChanged: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}

written to me by januw a *and explained by *Aakash Kumar link,
I tried every way to work on index in PhotoViewGallery.builder but I can't get away with it.
I'm new in flutter, can someone help me?
Special thanks mario

like image 314
attila Avatar asked Mar 04 '23 09:03

attila


1 Answers

You need to add controller:

int firstPage = 2;
PageController _pageController = PageController(initialPage: firstPage);

and attach it to your builder

PhotoViewGallery.builder(
    itemCount: listaPagine.length,
    pageController: _pageController,
    builder: (BuildContext context, int index) {
      String myImg = listaPagine[index];

      return PhotoViewGalleryPageOptions(
        imageProvider: NetworkImage(myImg),
      );
    },
    onPageChanged: (int index) {
      setState(() {
        _currentIndex = index;
      });
    },
  ),
like image 59
whitebug Avatar answered Mar 06 '23 08:03

whitebug