#flutter #flutter-layout #flutter-pageview
Вопрос:
Я пытался привести карусель в движение, но, к сожалению, при просмотре страниц возникли некоторые проблемы, пока я работал над ней
class Carousel extends StatelessWidget {
Corousel({Key key}) : super(key: key);
PageController controller = PageController(initialPage: 2);
@override
Widget build(BuildContext context) {
return Padding(padding: EdgeInsets.all(30),
child:Stack(alignment: AlignmentDirectional.bottomCenter,
children: [
CorouselController(controller: controller,),
CorouselGalary(controller: controller)
],
),
);
}
}
class CorouselController extends StatelessWidget{
PageController controller=PageController();
CorouselController({Key key,this.controller}):super(key: key);
_scrollRight(){
if(controller.hasClients){
debugPrint(controller.position.toString());
}else{
debugPrint("not connected");
}
}
_scrollLeft(){
if(controller.hasClients){
debugPrint(controller.position.toString());
}else{
debugPrint("not connected");
}
}
@override
Widget build(BuildContext context) {
return Row(children: [
IconButton( icon: Icon(Icons.chevron_left_sharp),color: Color(0xff000000),onPressed: (){
_scrollLeft();
},),
Expanded(
child: Container(
color: Color(0x00000000),alignment: AlignmentDirectional.bottomCenter,
child: Icon(Icons.album_outlined),
),
),
IconButton( icon: Icon(Icons.chevron_right_sharp),color: Color(0xff000000),onPressed: (){
_scrollRight();
}),
],);
}
}
class CorouselGalary extends StatelessWidget{
PageController controller=PageController();
CorouselGalary({Key key,this.controller}):super(key: key);
@override
Widget build(BuildContext context) {
return PageView(
physics:AlwaysScrollableScrollPhysics(),
dragStartBehavior: DragStartBehavior.down,
scrollDirection: Axis.horizontal,
controller: controller,
children: const <Widget>[
Center(
child: Text('First Page'),
),
Center(
child: Text('Second Page'),
),
Center(
child: Text('Third Page'),
)
],
);
}
}
Вывод выглядит так
как и кнопки со значками, они действуют как отключенные, даже просмотр страниц реагирует на жест. но если я попробую это
return Padding(padding: EdgeInsets.all(30),
child:Stack(alignment: AlignmentDirectional.bottomCenter,
children: [
CorouselController(controller: controller,),
//CorouselGalary(controller: controller)
],//just remove page view from stack
),
);
Кнопка отвечает на движение мыши
Должна быть какая-то проблема с просмотром страниц, как мне ее решить?
Ответ №1:
Элементы в стеке всегда стараются скрыть весь размер виджетов. Я предполагаю, что класс galary охватывает всю страницу и не позволяет вам нажимать кнопки. (может быть, цвет галары прозрачный?).
Вместо стека вы можете попытаться поместить его в горизонтальную колонку, например: [button, galary, button]
Возможно, это может решить вашу проблему.
Я не уверен в ответе. Но, полагаю, попытка не повредит.
PS: У меня нет доступа к комментариям. Поэтому, пожалуйста, рассматривайте это как комментарий.
Редактировать:
Для вашего понимания, почему вы не можете получить доступ к кнопкам
Container(
color: Colors.blue,
child: PageView()
),
Попробуйте изменить вышеизложенное следующим образом (ограниченная ширина) — вы найдете кнопки и сможете получить к ним доступ
Container(
width: 500,
color: Colors.blue,
child: PageView()
),
Ниже приведен пример, который я попробовал в DartPad
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Carousel();
}
}
class Carousel extends StatelessWidget {
Carousel({Key key}) : super(key: key);
final PageController controller = PageController(initialPage: 2);
@override
Widget build(BuildContext context) {
return Padding(padding: EdgeInsets.all(30),
child:Stack(alignment: AlignmentDirectional.bottomCenter,
children: [
CorouselController(controller: controller,),
CorouselGalary(controller: controller)
],
),
);
}
}
class CorouselController extends StatelessWidget{
final PageController controller;
CorouselController({Key key,this.controller}):super(key: key);
_scrollRight(){
if(controller.hasClients){
debugPrint(controller.position.toString());
}else{
debugPrint("not connected");
}
}
_scrollLeft(){
if(controller.hasClients){
debugPrint(controller.position.toString());
}else{
debugPrint("not connected");
}
}
@override
Widget build(BuildContext context) {
return Row(children: [
IconButton( icon: Icon(Icons.chevron_left_sharp),color: Color(0xff000000),onPressed: (){
_scrollLeft();
},),
Expanded(
child: Container(
color: Color(0x00000000),alignment: AlignmentDirectional.bottomCenter,
child: Icon(Icons.album_outlined),
),
),
IconButton( icon: Icon(Icons.chevron_right_sharp),color: Color(0xff000000),onPressed: (){
_scrollRight();
}),
],);
}
}
class CorouselGalary extends StatelessWidget{
final PageController controller;
CorouselGalary({Key key,this.controller}):super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: 500,
color: Colors.blue,
child: PageView(
physics:AlwaysScrollableScrollPhysics(),
dragStartBehavior: DragStartBehavior.down,
scrollDirection: Axis.horizontal,
controller: controller,
children: const <Widget>[
Center(
child: Text('First Page'),
),
Center(
child: Text('Second Page'),
),
Center(
child: Text('Third Page'),
)
],
),
);
}
}
Комментарии:
1. Я ценю ваш ответ, но проблема в том, что кнопка также не работает при просмотре страницы
2. Я хотел сказать, что просмотр страницы закрывает от вас кнопки, делая его недоступным. Я бы предположил, что вы можете поместить просмотр страницы либо в размерный ящик, либо в контейнер с ограниченной шириной (скажем, 500 или меньше). Затем вы обнаружите, что можете получить доступ к кнопкам. Если вы все еще не понимаете, попробуйте изменить его так, как я отредактировал в разделе ответов.